package org.jeecg.modules.demo.crm.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.crm.entity.CAcceptanceRecord;
import org.jeecg.modules.demo.crm.entity.CTask;
import org.jeecg.modules.demo.crm.mapper.CSubProjectMapper;
import org.jeecg.modules.demo.crm.service.ICAcceptanceRecordService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.crm.service.ICCommonService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 验收记录表
 * @Author: jeecg-boot
 * @Date:   2025-06-19
 * @Version: V1.0
 */
@Api(tags="验收记录表")
@RestController
@RequestMapping("/crm/cAcceptanceRecord")
@Slf4j
public class CAcceptanceRecordController extends JeecgController<CAcceptanceRecord, ICAcceptanceRecordService> {
	@Autowired
	private ICAcceptanceRecordService cAcceptanceRecordService;

	 @Autowired
	 private ICCommonService commonService;
	 @Autowired
	 private CSubProjectMapper cSubProjectMapper;

	/**
	 * 分页列表查询
	 *
	 * @param cAcceptanceRecord
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "验收记录表-分页列表查询")
	@ApiOperation(value="验收记录表-分页列表查询", notes="验收记录表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CAcceptanceRecord>> queryPageList(CAcceptanceRecord cAcceptanceRecord,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														  @RequestParam(name="isApp", defaultValue="0") Integer isApp,
								   HttpServletRequest req) {

		Boolean permissionCheck = commonService.permissionCheck();
		if(permissionCheck){
			//必须projectId subProjectId 都不能空
			if("-1".equals(cAcceptanceRecord.getProjectId())){
				cAcceptanceRecord.setProjectId(null);
			}
			if("-1".equals(cAcceptanceRecord.getSubProjectId())){
				cAcceptanceRecord.setSubProjectId(null);
			}
		}
		/*if(permissionCheck && isApp == 0){
			//必须projectId subProjectId 都不能空
			if(StringUtils.isEmpty(cAcceptanceRecord.getProjectId())){
				cAcceptanceRecord.setProjectId("-1");
			}
			if(StringUtils.isEmpty(cAcceptanceRecord.getSubProjectId())){
				cAcceptanceRecord.setSubProjectId("-1");
			}
		}if(permissionCheck) {
			//app 查看
			if(permissionCheck){//不是管理员
				//只能查看自己提交的验收记录
				LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
				cAcceptanceRecord.setAcceptancePerson(sysUser.getId());
			}
		}*/
		if(cAcceptanceRecord.getAcceptanceStatus()!=null && "全部".equals(cAcceptanceRecord.getAcceptanceStatus())){
			cAcceptanceRecord.setAcceptanceStatus(null);
		}
        // 自定义查询规则
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自定义多选的查询规则为：LIKE_WITH_OR
        customeRuleMap.put("subProjectId", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("acceptanceStatus", QueryRuleEnum.LIKE_WITH_OR);
        QueryWrapper<CAcceptanceRecord> queryWrapper = QueryGenerator.initQueryWrapper(cAcceptanceRecord, req.getParameterMap(),customeRuleMap);
		queryWrapper = commonService.permissionDetectionColumn(queryWrapper,"acceptance_person");
		if(permissionCheck){
			//如果不是管理员
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			String projectId = cSubProjectMapper.projectPermissions(sysUser.getId());
			if(projectId == null){
				projectId = "-1";
			}
			List<Long> idList = Arrays.stream(projectId.split(","))
					.map(String::trim)
					.filter(StringUtils::isNotBlank)
					.map(Long::valueOf)
					.collect(Collectors.toList());
			queryWrapper.in("project_id", idList);
			//只能查看自己提交的验收记录
			cAcceptanceRecord.setAcceptancePerson(sysUser.getId());
		}

		Page<CAcceptanceRecord> page = new Page<CAcceptanceRecord>(pageNo, pageSize);
		IPage<CAcceptanceRecord> pageList = cAcceptanceRecordService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param cAcceptanceRecord
	 * @return
	 */
	@AutoLog(value = "验收记录表-添加")
	@ApiOperation(value="验收记录表-添加", notes="验收记录表-添加")
	@RequiresPermissions("crm:c_acceptance_record:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CAcceptanceRecord cAcceptanceRecord) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		cAcceptanceRecord.setAcceptancePerson(sysUser.getId());
		cAcceptanceRecord.setAcceptanceStatus("审核中");
		cAcceptanceRecordService.save(cAcceptanceRecord);
		return Result.OK("审核中，请联系项目经理审核！");
	}


	 /**
	  *  编辑
	  *
	  * @param cAcceptanceRecord
	  * @return
	  */
	 @AutoLog(value = "验收记录表-编辑")
	 @ApiOperation(value="验收记录表-编辑", notes="验收记录表-编辑")
	 @RequiresPermissions("crm:c_acceptance_record:edit")
	 @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> edit(@RequestBody CAcceptanceRecord cAcceptanceRecord) {
		 cAcceptanceRecordService.edit(cAcceptanceRecord);
		 return Result.OK("编辑成功!");
	 }

	 /**
	  *  编辑
	  *
	  * @param cAcceptanceRecord
	  * @return
	  */
	 @AutoLog(value = "验收记录表-编辑")
	 @ApiOperation(value="验收记录表-编辑", notes="验收记录表-编辑")
	 @RequiresPermissions("crm:c_acceptance_record:edit")
	 @RequestMapping(value = "/appEdit", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> appEdit(@RequestBody CAcceptanceRecord cAcceptanceRecord) {
		 cAcceptanceRecordService.appEdit(cAcceptanceRecord);
		 return Result.OK("编辑成功!");
	 }


	 @AutoLog(value = "验收记录表-审核")
	 @ApiOperation(value="验收记录表-审核", notes="验收记录表-审核")
	 @RequiresPermissions("crm:c_acceptance_record:audit")
	 @RequestMapping(value = "/audit", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> audit(@RequestBody CAcceptanceRecord cAcceptanceRecord) {
		 cAcceptanceRecordService.audit(cAcceptanceRecord);
		 return Result.OK("审核成功!");
	 }


	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "验收记录表-通过id删除")
	@ApiOperation(value="验收记录表-通过id删除", notes="验收记录表-通过id删除")
	@RequiresPermissions("crm:c_acceptance_record:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		cAcceptanceRecordService.removeById(id);
		return Result.OK("删除成功!");
	}
	

	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "验收记录表-通过id查询")
	@ApiOperation(value="验收记录表-通过id查询", notes="验收记录表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CAcceptanceRecord> queryById(@RequestParam(name="id",required=true) String id) {
		CAcceptanceRecord cAcceptanceRecord = cAcceptanceRecordService.getById(id);
		if(cAcceptanceRecord==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(cAcceptanceRecord);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param cAcceptanceRecord
    */
    @RequiresPermissions("crm:c_acceptance_record:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CAcceptanceRecord cAcceptanceRecord) {
        return super.exportXls(request, cAcceptanceRecord, CAcceptanceRecord.class, "验收记录表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("crm:c_acceptance_record:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CAcceptanceRecord.class);
    }


	 @ApiOperation(value="验收记录表-状态", notes="验收记录表-状态")
	 @GetMapping(value = "/statusCount")
	 public Result<Map<String,Long>> statusCount(CAcceptanceRecord acceptanceRecord,
												 HttpServletRequest req) {
		 Map<String,Long> data = cAcceptanceRecordService.statusCount(acceptanceRecord,req);
		 return Result.OK(data);
	 }
}
